﻿using System;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using AutoItX3Lib;
using System.Drawing;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Xml.Linq;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using CommonFunction;
using System.Data;

namespace Robot_Roulettist_Facebook
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public partial class Roulettist : Form
    {
        CancellationTokenSource tokenSource = null;
        Task taskPlayGame = null;
        DataTable processList = null;

        public Roulettist()
        {
            InitializeComponent();

            InitForm();
        }

        private void Roulettist_Load(object sender, EventArgs e)
        {
            FB_Common.HANDLER = this.Handle;
            LoadMainData();
            LoadListGameWindows();
        }

        private void Roulettist_FormClosing(object sender, FormClosingEventArgs e)
        {
            var confirm = MessageBox.Show("Do you want to quit the Roulettist ?", "Roulettist Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (confirm != System.Windows.Forms.DialogResult.Yes) e.Cancel = true;
        }

        private void btnCofiguration_Click(object sender, EventArgs e)
        {
            SetForegroundWindow((IntPtr)this.lstProcesses.SelectedValue);
        }

        private void btnPlayGame_Click(object sender, EventArgs e)
        {
            if (!ValidateBeforePlayGame()) return;
            this.Cursor = Cursors.WaitCursor;

            try
            {
                ChangeTitleOfWindowGame();

                SwitchStatusOfPlayGame();

                Updated();

                btnStart_Click(btnStart, e);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {            
            this.Cursor = Cursors.WaitCursor;

            AccessData objData = new AccessData();
            var xmlDoc = objData.GetData_Facebook();
            objData = null;
            if (!FB_Common.InitGameInfo(xmlDoc))
            {
                MessageBox.Show("The Roulettist can not initialize the information of game", "Initializing Game Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Cursor = Cursors.Default;
                return;
            }

            FB_Common.GameStatus = FB_Common.GAME_STATUS.STARTED;
            
            SwitchStatusOfStartOrStopBOT();

            SelectBetRate();

            tokenSource = new CancellationTokenSource();
            Action playGame = delegate() { this.PlayGame(); };
            taskPlayGame = new Task(playGame);
            taskPlayGame.Start();

            this.Cursor = Cursors.Default;

            return;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("Do you want to STOP the Roulettist ?", "Roulettist Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (confirm != System.Windows.Forms.DialogResult.Yes) return;

            this.Cursor = Cursors.WaitCursor;

            FB_Common.GameStatus = FB_Common.GAME_STATUS.STOPPED;

            ResetCoins();

            tokenSource.Cancel();
            tokenSource = null;
            taskPlayGame = null;

            SwitchStatusOfStartOrStopBOT();

            this.Cursor = Cursors.Default;
        }

        #region "processing the behaviour of controls"

        private void SwitchStatusOfPlayGame()
        {
            grpSelectWindow.Enabled = false;
            grpConfig.Enabled = false;
            btnPlayGame.Enabled = false;
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            txtRoulettistName.Enabled = false;
            mnuItemPlay.Enabled = false;
        }

        private void ChangeTitleOfWindowGame()
        {
            this.Text = string.Format("Roulettist Facebook - {0}", txtRoulettistName.Text.Trim());
            this.trayIcon.BalloonTipTitle = string.Format("Roulete Bot for Facebook - {0}", txtRoulettistName.Text.Trim());
            this.trayIcon.Text = string.Format("Roulete Bot for Facebook - {0}", txtRoulettistName.Text.Trim());

            //AutoItX3 autoit = new AutoItX3();
            //autoit.WinSetTitle(lstProcesses.Text, "", this.Text);
            //foreach (DataRow row in processList.Rows)
            //{
            //    if (row["proID"] == lstProcesses.SelectedValue)
            //    {
            //        row["proName"] = this.Text;
            //        break;
            //    }
            //}
            //autoit = null;

            return;
        }

        private void SwitchStatusOfStartOrStopBOT()
        {
            var enabled = false;
            
            if (FB_Common.GameStatus == FB_Common.GAME_STATUS.STARTED)
                enabled = true;
            else
                enabled = false;

            setEnableButton(btnStart, !enabled);
            setEnableButton(btnStop, enabled);

            setEnableMenuItem(mnuItemStart, !enabled);
            setEnableMenuItem(mnuItemStop, enabled);

            return;
        }

        #endregion

        #region "validating before playing game"

        private bool ValidateBeforePlayGame()
        {   
            //validate the name of roulettist is empty or not
            if (string.IsNullOrEmpty(txtRoulettistName.Text.Trim()))
            {
                MessageBox.Show("Please enter the name of Roulettist before playing the game", "Roulettist Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                txtRoulettistName.Focus();

                return false;
            }

            //validate selected window game
            if (lstProcesses.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select a window of Roulettist before playing the game", "Roulettist Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                lstProcesses.Focus();

                return false;
            }

            return true;
        }

        #endregion

        #region "load data of configuration"

        private void LoadListGameWindows()
        {   
            processList = new DataTable();
            DataColumn col = new DataColumn("proID", typeof(System.IntPtr));
            processList.Columns.Add(col);
            col = new DataColumn("proName", typeof(System.String));
            processList.Columns.Add(col);

            var objProcesses = Process.GetProcesses().Where(p => !string.IsNullOrEmpty(p.MainWindowTitle))
                .Select(p => new { proID = p.MainWindowHandle, proName = p.MainWindowTitle }).ToList();

            foreach (var obj in objProcesses)
            {
                var row = processList.NewRow();
                row["proID"] = obj.proID;
                row["proName"] = obj.proName;
                processList.Rows.Add(row);
            }

            lstProcesses.DataSource = processList;
            lstProcesses.DisplayMember = "proName";
            lstProcesses.ValueMember = "proID";            
        }

        private void LoadMainData()
        {
            AccessData objData = null;
            XmlDocument xmlData = null;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();

                txtRoulettistName.Text = xmlData.GetRoulettistName();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading main data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }
        }

        private bool Updated()
        {
            AccessData objData = null;
            XmlDocument xmlData = null;
            bool success = false;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();

                xmlData.SetRoulettistName(txtRoulettistName.Text);

                objData.SaveData_Facebook(xmlData);

                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }

            return success;
        }

        #endregion

        #region "Play game"

        private void PlayGame()
        {
            bool breakGame = false;
            while (FB_Common.GameStatus == FB_Common.GAME_STATUS.STARTED)
            {
                if (Ready())
                {
                    var numberResult = Result();
                    if (numberResult == -1)
                    {
                        Thread.Sleep(2000);
                        continue;
                    }

                    Calculation(numberResult);
                    UpdateInfoOfGame();

                    if (FB_Common.TOTAL_WINNINGS * 1000 >= FB_Common.STOP_WINNING || Convert.ToUInt32(Math.Abs(FB_Common.TOTAL_WINNINGS)) * 1000 >= FB_Common.STOP_LOSING)
                    {
                        breakGame = true;
                        break;
                    }

                    ResetCoins();

                    if (FB_Common.STRATEGY_TYPE == FB_Common.STRATEGY.Following)
                        PlayFollowingStrategy(numberResult);
                    else
                        PlayOtherStrategy();

                    ConfirmBet();

                    Thread.Sleep(FB_Common.SLEEP_SECOND);
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }

            if (breakGame)
            {
                ResetCoins();

                FB_Common.GameStatus = FB_Common.GAME_STATUS.STOPPED;
                tokenSource.Cancel();                
                tokenSource = null;
                taskPlayGame = null;

                SwitchStatusOfStartOrStopBOT();
            }
        }

        private void PlayFollowingStrategy(Int16 numberResult)
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED) return;

            //black / red
            FB_Common.LOST_FOLLOW_BLACK_RED = FB_Common.LOST_FOLLOW_BLACK_RED > 29 ? (UInt16)29 : FB_Common.LOST_FOLLOW_BLACK_RED;
            var noOfClick = FB_Common.FOLLOWING_VALUES[(int)FB_Common.STRATEGIES.BLACK_RED, FB_Common.LOST_FOLLOW_BLACK_RED];
            if (noOfClick > 0)
            {
                BetFollowingBlackRed(noOfClick, numberResult);
            }
            Thread.Sleep(500);

            //high / low
            FB_Common.LOST_FOLLOW_HIGH_LOW = FB_Common.LOST_FOLLOW_HIGH_LOW > 29 ? (UInt16)29 : FB_Common.LOST_FOLLOW_HIGH_LOW;
            noOfClick = FB_Common.FOLLOWING_VALUES[(int)FB_Common.STRATEGIES.HIGH_LOW, FB_Common.LOST_FOLLOW_HIGH_LOW];
            if (noOfClick > 0)
            {
                BetFollowingHighLow(noOfClick, numberResult);
            }
            Thread.Sleep(500);

            //even / odd
            FB_Common.LOST_FOLLOW_EVEN_ODD = FB_Common.LOST_FOLLOW_EVEN_ODD > 29 ? (UInt16)29 : FB_Common.LOST_FOLLOW_EVEN_ODD;
            noOfClick = FB_Common.FOLLOWING_VALUES[(int)FB_Common.STRATEGIES.EVEN_ODD, FB_Common.LOST_FOLLOW_EVEN_ODD];
            if (noOfClick > 0)
            {
                BetFollowingEvenOdd(noOfClick, numberResult);
            }
        }

        private void PlayOtherStrategy()
        {
            PlayBlackRed();
            Thread.Sleep(500);

            PlayEvenOdd();
            Thread.Sleep(500);

            PlayHighLow();
            Thread.Sleep(500);

            PlayDozens();
            Thread.Sleep(500);

            PlayColumns();
            Thread.Sleep(500);

            PlayNumbers();
        }

        private void BetFollowingBlackRed(UInt16 noOfClick, Int16 numberResult)
        {
            AutoItX3 autoit = new AutoItX3();
            if (IsRed(numberResult))
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.RED_X, FB_Common.RED_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            else
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.BLACK_X, FB_Common.BLACK_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            autoit = null;
        }

        private void BetFollowingEvenOdd(UInt16 noOfClick, Int16 numberResult)
        {
            AutoItX3 autoit = new AutoItX3();
            if (IsEven(numberResult))
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.EVEN_X, FB_Common.EVEN_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            else
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.ODD_X, FB_Common.ODD_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            autoit = null;
        }

        private void BetFollowingHighLow(UInt16 noOfClick, Int16 numberResult)
        {
            AutoItX3 autoit = new AutoItX3();
            if (IsHigh(numberResult))
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.HIGH_X, FB_Common.HIGH_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            else
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.LOW_X, FB_Common.LOW_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }
            autoit = null;
        }

        private void PlayBlackRed()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_BR <= 0) return;

            AutoItX3 autoit = new AutoItX3();

            var index = FB_Common.WAIT_BLACK - FB_Common.WAITING_BR;
            UInt16 noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.BLACK_RED, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.BLACK_X, FB_Common.BLACK_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_RED - FB_Common.WAITING_BR;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.BLACK_RED, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.RED_X, FB_Common.RED_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            autoit = null;
        }

        private void PlayHighLow()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_HL <= 0) return;

            AutoItX3 autoit = new AutoItX3();

            var index = FB_Common.WAIT_HIGH - FB_Common.WAITING_HL;
            UInt16 noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.HIGH_LOW, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.HIGH_X, FB_Common.HIGH_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_LOW - FB_Common.WAITING_HL;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.HIGH_LOW, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.LOW_X, FB_Common.LOW_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            autoit = null;
        }

        private void PlayEvenOdd()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_EO <= 0) return;

            AutoItX3 autoit = new AutoItX3();

            var index = FB_Common.WAIT_EVEN - FB_Common.WAITING_EO;
            UInt16 noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.EVEN_ODD, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.EVEN_X, FB_Common.EVEN_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_ODD - FB_Common.WAITING_EO;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.EVEN_ODD, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.ODD_X, FB_Common.ODD_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            autoit = null;
        }

        private void PlayDozens()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_DZ <= 0) return;

            AutoItX3 autoit = new AutoItX3();

            var index = FB_Common.WAIT_DOZEN1 - FB_Common.WAITING_DZ;
            UInt16 noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.DOZENS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.DOZEN1_X, FB_Common.DOZEN_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_DOZEN2 - FB_Common.WAITING_DZ;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.DOZENS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.DOZEN2_X, FB_Common.DOZEN_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_DOZEN3 - FB_Common.WAITING_DZ;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.DOZENS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.DOZEN3_X, FB_Common.DOZEN_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            autoit = null;
        }

        private void PlayColumns()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_CL <= 0) return;

            AutoItX3 autoit = new AutoItX3();

            var index = FB_Common.WAIT_COLUMN1 - FB_Common.WAITING_CL;
            UInt16 noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.COLUMNS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.COL1_X, FB_Common.COL1_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_COLUMN2 - FB_Common.WAITING_CL;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.COLUMNS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.COL2_X, FB_Common.COL2_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            index = FB_Common.WAIT_COLUMN3 - FB_Common.WAITING_CL;
            noOfClick = 0;
            index = index > 29 ? 29 : index;
            if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.COLUMNS, index];
            if (noOfClick >= 0)
            {
                autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.COL3_X, FB_Common.COL3_Y);
                FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2] = (UInt32)FB_Common.BET_RATE * noOfClick;
            }

            autoit = null;
        }

        private void PlayNumbers()
        {
            if (FB_Common.GameStatus != FB_Common.GAME_STATUS.STARTED || FB_Common.WAITING_NO <= 0) return;

            AutoItX3 autoit = new AutoItX3();
            var cols1 = new UInt16[] { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36 };
            var cols2 = new UInt16[] { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
            
            for (int i = 0; i < 37; i++)
            {
                var index = FB_Common.WAIT_NUMBER[i] - FB_Common.WAITING_NO;
                UInt16 noOfClick = 0;
                index = index > 29 ? 29 : index;
                if (index >= 0) noOfClick = FB_Common.OTHER_VALUES[(int)FB_Common.STRATEGIES.NUMBERS, index];
                if (noOfClick >= 0)
                {
                    if (i == 0)
                        autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.NO_0_X, FB_Common.NO_0_Y);
                    else if (cols1.Contains((UInt16)i))
                        autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.NO_COL1_X, FB_Common.NO_COL1_Y);
                    else if (cols2.Contains((UInt16)i))
                        autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.NO_COL2_X, FB_Common.NO_COL2_Y);
                    else
                        autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", noOfClick, FB_Common.NO_COL3_X, FB_Common.NO_COL3_Y);
                    FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, i] = (UInt32)FB_Common.BET_RATE * noOfClick;
                }
                Thread.Sleep(200);
            }
            
            autoit = null;
        }

        private void Calculation(Int16 numberResult)
        {
            if (FB_Common.LAST_NUMBER_RESULT == -1) FB_Common.LAST_NUMBER_RESULT = numberResult;

            bool oldRed = IsRed(FB_Common.LAST_NUMBER_RESULT);
            bool newRed = IsRed(numberResult);
            bool oldEven = IsEven(FB_Common.LAST_NUMBER_RESULT);
            bool newEven = IsEven(numberResult);
            bool oldHigh = IsHigh(FB_Common.LAST_NUMBER_RESULT);
            bool newHigh = IsHigh(numberResult);

            //calc for following strategy
            if (numberResult == 0)
            {
                FB_Common.LOST_FOLLOW_BLACK_RED++;
                FB_Common.LOST_FOLLOW_HIGH_LOW++;
                FB_Common.LOST_FOLLOW_EVEN_ODD++;
                FB_Common.WAIT_BLACK++;
                FB_Common.WAIT_RED++;
                FB_Common.WAIT_LOW++;
                FB_Common.WAIT_HIGH++;
                FB_Common.WAIT_EVEN++;
                FB_Common.WAIT_ODD++;
                FB_Common.WAIT_COLUMN1++;
                FB_Common.WAIT_COLUMN2++;
                FB_Common.WAIT_COLUMN3++;
                FB_Common.WAIT_DOZEN1++;
                FB_Common.WAIT_DOZEN2++;
                FB_Common.WAIT_DOZEN3++;
                FB_Common.WAIT_NUMBER[0] = 0;

                for (int i = 1; i < 37; i++)
                {
                    FB_Common.WAIT_NUMBER[i]++;
                    FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, i];
                }
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, 0];

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1];                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2];                
            }
            else
            {
                if (oldRed == newRed)
                    FB_Common.LOST_FOLLOW_BLACK_RED = 0;
                else
                    FB_Common.LOST_FOLLOW_BLACK_RED++;

                if (oldEven == newEven)
                    FB_Common.LOST_FOLLOW_EVEN_ODD = 0;
                else
                    FB_Common.LOST_FOLLOW_EVEN_ODD++;

                if (oldHigh == newHigh)
                    FB_Common.LOST_FOLLOW_HIGH_LOW = 0;
                else
                    FB_Common.LOST_FOLLOW_HIGH_LOW++;
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, 0];
            }

            //calc for black/red strategy
            if (newRed == false)
            {
                FB_Common.WAIT_RED++;
                FB_Common.WAIT_BLACK = 0;
                
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1];
            }
            else
            {
                FB_Common.WAIT_BLACK++;
                FB_Common.WAIT_RED = 0;

                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1];
            }

            //calc for high/low strategy
            if (IsHigh(numberResult))
            {
                FB_Common.WAIT_LOW++;
                FB_Common.WAIT_HIGH = 0;

                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1];
            }
            else
            {
                FB_Common.WAIT_HIGH++;
                FB_Common.WAIT_LOW = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1];
            }

            //calc for EVEN/ODD strategy
            if (IsEven(numberResult))
            {
                FB_Common.WAIT_ODD++;
                FB_Common.WAIT_EVEN = 0;

                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1];
            }
            else
            {
                FB_Common.WAIT_EVEN++;
                FB_Common.WAIT_ODD = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1];
            }

            //calc for DOZENS strategy
            var dozenResult = DozenIndex(numberResult);
            if (dozenResult== FB_Common.DOZENS.D1)
            {
                FB_Common.WAIT_DOZEN2++;
                FB_Common.WAIT_DOZEN3++;
                FB_Common.WAIT_DOZEN1 = 0;

                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2];
            }
            else if (dozenResult == FB_Common.DOZENS.D2)
            {
                FB_Common.WAIT_DOZEN1++;
                FB_Common.WAIT_DOZEN3++;
                FB_Common.WAIT_DOZEN2 = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2];
            }
            else
            {
                FB_Common.WAIT_DOZEN1++;
                FB_Common.WAIT_DOZEN2++;
                FB_Common.WAIT_DOZEN3 = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2];
            }

            //calc for COLUMNS strategy
            var columnResult = ColumnIndex(numberResult);
            if (columnResult == FB_Common.COLUMNS.C1)
            {
                FB_Common.WAIT_COLUMN2++;
                FB_Common.WAIT_COLUMN3++;
                FB_Common.WAIT_COLUMN1 = 0;

                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2];
            }
            else if (columnResult == FB_Common.COLUMNS.C2)
            {
                FB_Common.WAIT_COLUMN1++;
                FB_Common.WAIT_COLUMN3++;
                FB_Common.WAIT_COLUMN2 = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2];
            }
            else
            {
                FB_Common.WAIT_COLUMN1++;
                FB_Common.WAIT_COLUMN2++;
                FB_Common.WAIT_COLUMN3 = 0;

                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0];
                FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1];
                FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2];
            }

            //calc for NUMBER strategy
            if (numberResult > 0)
            {
                for (int i = 0; i < 37; i++)
                {
                    if (numberResult == i)
                    {
                        FB_Common.WAIT_NUMBER[i] = 0;
                        FB_Common.TOTAL_WINNINGS += FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, i];
                    }
                    else
                    {
                        FB_Common.WAIT_NUMBER[i]++;
                        FB_Common.TOTAL_WINNINGS -= FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, i];
                    }
                }
            }

            FB_Common.LAST_NUMBER_RESULT = numberResult;

            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 0] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.BLACK_RED, 1] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 0] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.HIGH_LOW, 1] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 0] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.EVEN_ODD, 1] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 0] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 1] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.COLUMNS, 2] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 0] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 1] = 0;
            FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.DOZENS, 2] = 0;
            for (int i = 0; i < 37; i++) FB_Common.TOTAL_BET_AMOUNT[(int)FB_Common.STRATEGIES.NUMBERS, i] = 0;

            return;
        }

        private void UpdateInfoOfGame()
        {
            setTextControl(lblBlack.Name, FB_Common.WAIT_BLACK.ToString());
            setTextControl(lblRed.Name, FB_Common.WAIT_RED.ToString());
            setTextControl(lblEven.Name, FB_Common.WAIT_EVEN.ToString());
            setTextControl(lblOdd.Name, FB_Common.WAIT_ODD.ToString());
            setTextControl(lblHigh.Name, FB_Common.WAIT_HIGH.ToString());
            setTextControl(lblLow.Name, FB_Common.WAIT_LOW.ToString());
            setTextControl(lblD1.Name, FB_Common.WAIT_DOZEN1.ToString());
            setTextControl(lblD2.Name, FB_Common.WAIT_DOZEN2.ToString());
            setTextControl(lblD3.Name, FB_Common.WAIT_DOZEN3.ToString());
            setTextControl(lblC1.Name, FB_Common.WAIT_COLUMN1.ToString());
            setTextControl(lblC2.Name, FB_Common.WAIT_COLUMN2.ToString());
            setTextControl(lblC3.Name, FB_Common.WAIT_COLUMN3.ToString());
            if (FB_Common.LAST_NUMBER_RESULT >= 0) setTextControl(lblLastNumber.Name, FB_Common.LAST_NUMBER_RESULT.ToString());

            var lblName = string.Empty;
            for (int i = 0; i < 37; i++)
            {
                lblName = string.Format("lbl{0}", i);
                setTextControl(lblName, FB_Common.WAIT_NUMBER[i].ToString());
            }
            string totalWinning = (FB_Common.TOTAL_WINNINGS * 1000).ToString("#,##0");
            setTextControl(lblTotalWinnings.Name, totalWinning);
            
            return;
        }

        delegate void SetTextCallback(string ctrlName, string text);

        private void setTextControl(string ctrlName, string text)
        {
            if (this.grpGameInfo.Controls[ctrlName].InvokeRequired)
            {
                SetTextCallback setText = new SetTextCallback(setTextControl);
                this.Invoke(setText, ctrlName, text);
            }
            else
                grpGameInfo.Controls[ctrlName].Text = text;
        }

        delegate void SetEnableButtonCallback(Button btn, bool isEnabled);

        private void setEnableButton(Button btn, bool isEnabled)
        {
            if (btn.InvokeRequired)
            {
                SetEnableButtonCallback setEnabled = new SetEnableButtonCallback(setEnableButton);
                this.Invoke(setEnabled, btn, isEnabled);
            }
            else
                btn.Enabled = isEnabled;
        }

        delegate void SetEnableMenuItemCallback(ToolStripItem item, bool isEnabled);
        private void setEnableMenuItem(ToolStripItem item, bool isEnabled)
        {   
            if (this.mnuStrip.InvokeRequired)
            {
                SetEnableMenuItemCallback setEnabled = new SetEnableMenuItemCallback(setEnableMenuItem);
                this.Invoke(setEnabled, item, isEnabled);
            }
            else
                item.Enabled = isEnabled;
        }

        #endregion

        #region "Integrating with browser game"

        private bool Ready()
        {
            try
            {
                if (FB_Common.PicReady == null)
                {
                    FB_Common.PicReady = (Bitmap)Bitmap.FromFile(FB_Common.ReadyFilePath);
                }

                var imgReady = CaptureImage(FB_Common.HANDLER, FB_Common.IMAGE_READY_X, FB_Common.IMAGE_READY_Y, FB_Common.IMAGE_WIDTH, FB_Common.IMAGE_HEIGHT);
                
                imgReady.Save(FB_Common.ResultFilePath);
                imgReady = Image.FromFile(FB_Common.ResultFilePath);
                
                var compare = FB_Common.PicReady.EqualTo(imgReady);
                
                imgReady.Dispose();

                return compare;
            }
            catch
            {
                return false;
            }
        }

        private Int16 Result()
        {
            Int16 returnValue = -1;
            try
            {
                var imgResult = CaptureImage(FB_Common.HANDLER, FB_Common.IMAGE_RESULT_X, FB_Common.IMAGE_RESULT_Y, FB_Common.IMAGE_RESULT_WIDTH, FB_Common.IMAGE_RESULT_HEIGHT);
                imgResult.Save(FB_Common.ResultFilePath);
                imgResult = Image.FromFile(FB_Common.ResultFilePath);

                var numberPath = string.Empty;
                var numberName = string.Empty;
                Image imgNumber = null;

                for (Int16 i = 0; i < 37; i++)
                {
                    numberName = string.Format("{0}.jpg", i);
                    numberPath = System.IO.Path.Combine(Application.StartupPath, "Data", numberName);
                    if (!System.IO.File.Exists(numberPath)) continue;

                    imgNumber = Image.FromFile(numberPath);
                    var compare = imgNumber.EqualTo(imgResult);
                    imgNumber.Dispose();

                    if (compare)
                    {
                        returnValue = i;
                        break;
                    }
                }
                imgResult.Dispose();
            }
            catch { }

            return returnValue;
        }

        private bool IsRed(Int16 numberResult)
        {
            var redNumbers = new Int16[] { 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 };

            return redNumbers.Contains(numberResult);
        }

        private bool IsHigh(Int16 numberResult)
        {
            return numberResult >= 19;
        }

        private bool IsEven(Int16 numberResult)
        {
            return (numberResult % 2m) == 0;
        }

        private FB_Common.COLUMNS ColumnIndex(Int16 numberResult)
        {
            FB_Common.COLUMNS columnResult = FB_Common.COLUMNS.C1;

            var cols1 = new Int16[] { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36 };
            var cols2 = new Int16[] { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
            var cols3 = new Int16[] { 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34 };

            if (cols1.Contains(numberResult))
                columnResult = FB_Common.COLUMNS.C1;
            else if (cols2.Contains(numberResult))
                columnResult = FB_Common.COLUMNS.C2;
            else if (cols3.Contains(numberResult))
                columnResult = FB_Common.COLUMNS.C3;

            return columnResult;
        }

        private FB_Common.DOZENS DozenIndex(Int16 numberResult)
        {
            FB_Common.DOZENS dozenResult = FB_Common.DOZENS.D1;

            if (numberResult <= 12)
                dozenResult = FB_Common.DOZENS.D1;
            else if (numberResult <= 24)
                dozenResult = FB_Common.DOZENS.D2;
            else
                dozenResult = FB_Common.DOZENS.D3;

            return dozenResult;
        }

        private void SelectBetRate()
        {
            AutoItX3 autoit = new AutoItX3();
            switch (FB_Common.BET_RATE)
            {
                case 10:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE1_X, FB_Common.BET_RATE_Y);
                    break;

                case 20:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE2_X, FB_Common.BET_RATE_Y);
                    break;

                case 50:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE3_X, FB_Common.BET_RATE_Y);
                    break;

                case 100:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE4_X, FB_Common.BET_RATE_Y);
                    break;

                case 200:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE5_X, FB_Common.BET_RATE_Y);
                    break;

                case 500:
                    autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.BET_RATE6_X, FB_Common.BET_RATE_Y);
                    break;

                default: break;
            }
            autoit = null;
        }

        private void ResetCoins()
        {
            AutoItX3 autoit = new AutoItX3();
            autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.RESET_X, FB_Common.RESET_Y);
            autoit = null;
        }

        private void ConfirmBet()
        {
            AutoItX3 autoit = new AutoItX3();
            autoit.ControlClick(this.Text, "", "[CLASS:Internet Explorer_Server; INSTANCE:1]", "LEFT", 1, FB_Common.SPIN_X, FB_Common.SPIN_Y);
            autoit = null;
        }

        #endregion

        #region "proccess images"
        
        private void AutoUpdate()
        {
            try
            {
                //capture ready image
                if (FB_Common.PicReady != null)
                {
                    FB_Common.PicReady.Dispose();
                    FB_Common.PicReady = null;                    
                }
                
                var image = CaptureImage(FB_Common.HANDLER, FB_Common.IMAGE_READY_X, FB_Common.IMAGE_READY_Y, FB_Common.IMAGE_WIDTH, FB_Common.IMAGE_HEIGHT);
                image.Save(FB_Common.ReadyFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                image.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Auto update failed ! \n{0}", ex.Message), "Auto update information", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr WindowHandle);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);        
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        public const int SRCCOPY = 13369376;

        private Image CaptureImage(IntPtr handle, int posX, int posY, int width, int height)
        {

            IntPtr hdcSrc = GetWindowDC(handle);
            
            IntPtr hdcDest = CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = SelectObject(hdcDest, hBitmap);
            BitBlt(hdcDest, 0, 0, width, height, hdcSrc, posX, posY, SRCCOPY);
            SelectObject(hdcDest, hOld);
            DeleteDC(hdcDest);
            ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            DeleteObject(hBitmap);

            return image;
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr hWnd = (IntPtr)lstProcesses.SelectedValue;
            
            //FixedWindowGame();
            
            //var image = CaptureImage(FB_Common.HANDLER, FB_Common.IMAGE_AMOUNT_X, FB_Common.IMAGE_AMOUNT_Y, FB_Common.IMAGE_AMOUNT_WIDTH, FB_Common.IMAGE_AMOUNT_HEIGHT);
            AutoItX3 autoit = new AutoItX3();
            
            var postX = autoit.ControlGetPosX(lstProcesses.Text, "", "[CLASS:Unity.WebPlayer; INSTANCE:1]");
            var postY = autoit.ControlGetPosY(lstProcesses.Text, "", "[CLASS:Unity.WebPlayer; INSTANCE:1]");
            var frameWidth = 0; var framehheight = 0;
            frameWidth = autoit.ControlGetPosWidth(lstProcesses.Text, "", "[CLASS:Unity.WebPlayer; INSTANCE:1]");
            framehheight = autoit.ControlGetPosHeight(lstProcesses.Text, "", "[CLASS:Unity.WebPlayer; INSTANCE:1]");

            var i = autoit.ControlClick("(1) Roulettist on Facebook - Mozilla Firefox", "", "[CLASS:Unity.WebPlayer; INSTANCE:1]", "LEFT", 1, 752, 552);
            //autoit.MouseMove(912, 604, 100);
            //autoit.Sleep(200);
            
            postX = postX + Convert.ToInt32(textBox1.Text);
            postY = postY + Convert.ToInt32(textBox2.Text);
            frameWidth = Convert.ToInt32(textBox3.Text);
            framehheight = Convert.ToInt32(textBox4.Text);

            var image = CaptureImage(hWnd, postX, postY, frameWidth, framehheight);

            image.Save(FB_Common.ResultFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            image.Dispose();
            autoit = null;
        }

        private void picContact_Click(object sender, EventArgs e)
        {
            frmRegistration frm = new frmRegistration();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnHidden_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void mnuItemMainWindow_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void mnuItemQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void mnuItemPlay_Click(object sender, EventArgs e)
        {
            btnPlayGame_Click(btnPlayGame, e);
        }

        private void mnuItemStart_Click(object sender, EventArgs e)
        {
            btnStart_Click(btnStart, e);
        }

        private void mnuItemStop_Click(object sender, EventArgs e)
        {
            btnStop_Click(btnStop, e);
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (processList == null) return;

            processList.DefaultView.RowFilter = "proName LIKE '%" + txtSearch.Text + "%'";
        }

        private void btnReloadProcesses_Click(object sender, EventArgs e)
        {
            LoadListGameWindows();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (UpdatedConfig()) MessageBox.Show("The data saved successfully", "Saving data configuration", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #region "Update data configuration"

        private bool UpdatedConfig()
        {
            AccessData objData = null;
            XmlDocument xmlData = null;
            bool success = false;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();

                xmlData.SetBetRate(cboBetRate.Text);
                if (string.IsNullOrEmpty(txtStopWinning.Text.Trim())) txtStopWinning.Text = "0";
                xmlData.SetStopWinning(txtStopWinning.Text);
                if (string.IsNullOrEmpty(txtStopLosing.Text.Trim())) txtStopLosing.Text = "0";
                xmlData.SetStopLosing(txtStopLosing.Text);

                xmlData.SetDoItFollowing(chkFollowing.Checked.ToString());

                //following strategy
                string ctrlName = string.Empty;
                var strategy = (FB_Common.STRATEGIES)cboFollowingStrategy.SelectedIndex;
                string[] followingValues = new string[30];

                for (int i = 1; i < 31; i++)
                {
                    ctrlName = string.Format("txtF{0}", i.ToString("00"));
                    followingValues[i - 1] = grpFollowing.Controls[ctrlName].Text;
                }
                switch (strategy)
                {
                    case FB_Common.STRATEGIES.BLACK_RED:
                        xmlData.SetFollowingBlackRedValues(followingValues);
                        break;

                    case FB_Common.STRATEGIES.EVEN_ODD:
                        xmlData.SetFollowingEvenOddValues(followingValues);
                        break;

                    case FB_Common.STRATEGIES.HIGH_LOW:
                        xmlData.SetFollowingHighLowValues(followingValues);
                        break;

                    default: break;
                }

                //other strategy
                strategy = (FB_Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex;
                string[] otherValues = new string[31];

                otherValues[0] = cboWaiting.Text;
                for (int i = 1; i < 31; i++)
                {
                    ctrlName = string.Format("txtO{0}", i.ToString("00"));
                    otherValues[i] = grpOtherStrategy.Controls[ctrlName].Text;
                }
                switch (strategy)
                {
                    case FB_Common.STRATEGIES.BLACK_RED:
                        xmlData.SetBlackRedValues(otherValues);
                        break;

                    case FB_Common.STRATEGIES.EVEN_ODD:
                        xmlData.SetEvenOddValues(otherValues);
                        break;

                    case FB_Common.STRATEGIES.HIGH_LOW:
                        xmlData.SetHighLowValues(otherValues);
                        break;

                    case FB_Common.STRATEGIES.DOZENS:
                        xmlData.SetDozenValues(otherValues);
                        break;

                    case FB_Common.STRATEGIES.COLUMNS:
                        xmlData.SetColumnValues(otherValues);
                        break;

                    case FB_Common.STRATEGIES.NUMBERS:
                        xmlData.SetNumberValues(otherValues);
                        break;

                    default: break;
                }

                objData.SaveData_Facebook(xmlData);

                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }

            return success;
        }
        
        #endregion

        #region "Load data configuration"

        public bool InitForm()
        {
            cboBetRate.SelectedIndex = 0;
            cboTypeOfStrategy.SelectedIndex = 0;
            cboWaiting.SelectedIndex = 0;
            cboFollowingStrategy.SelectedIndex = 0;

            LoadOtherStrategy(FB_Common.STRATEGIES.BLACK_RED);
            LoadFollowingStrategy(FB_Common.STRATEGIES.BLACK_RED);

            LoadConfigData();

            return true;
        }

        private void LoadConfigData()
        {
            AccessData objData = null;
            XmlDocument xmlData = null;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();

                cboBetRate.Text = xmlData.GetBetRate();
                txtStopWinning.Text = xmlData.GetStopWinning();
                txtStopLosing.Text = xmlData.GetStopLosing();

                chkFollowing.Checked = (xmlData.GetDoItFollowing() == "True");
                grpFollowing.Enabled = chkFollowing.Checked;
                chkOtherStrategy.Checked = !chkFollowing.Checked;
                grpOtherStrategy.Enabled = chkOtherStrategy.Checked;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }
        }

        private void LoadFollowingStrategy(FB_Common.STRATEGIES strategy)
        {
            AccessData objData = null;
            XmlDocument xmlData = null;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();


                XmlNode strategyData = null;
                string ctrlName = string.Empty;
                string nodeName = string.Empty;
                string keyNode = string.Empty;

                switch (strategy)
                {
                    case FB_Common.STRATEGIES.BLACK_RED:
                        strategyData = xmlData.GetFollowingBlackRedValues();
                        keyNode = "BR";
                        break;

                    case FB_Common.STRATEGIES.EVEN_ODD:
                        strategyData = xmlData.GetFollowingEvenOddValues();
                        keyNode = "EO";
                        break;

                    case FB_Common.STRATEGIES.HIGH_LOW:
                        strategyData = xmlData.GetFollowingHighLowValues();
                        keyNode = "HL";
                        break;

                    default: return;
                }

                for (int i = 1; i < 31; i++)
                {
                    ctrlName = string.Format("txtF{0}", i.ToString("00"));
                    nodeName = string.Format("{0}{1}", keyNode, i.ToString("00"));
                    grpFollowing.Controls[ctrlName].Text = strategyData[nodeName].InnerText;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }
        }

        private void LoadOtherStrategy(FB_Common.STRATEGIES strategy)
        {
            AccessData objData = null;
            XmlDocument xmlData = null;

            try
            {
                objData = new AccessData();
                xmlData = objData.GetData_Facebook();


                XmlNode strategyData = null;
                string ctrlName = string.Empty;
                string nodeName = string.Empty;
                string keyNode = string.Empty;

                switch (strategy)
                {
                    case FB_Common.STRATEGIES.BLACK_RED:
                        strategyData = xmlData.GetBlackRedValues();
                        keyNode = "BR";
                        break;

                    case FB_Common.STRATEGIES.EVEN_ODD:
                        strategyData = xmlData.GetEvenOddValues();
                        keyNode = "EO";
                        break;

                    case FB_Common.STRATEGIES.HIGH_LOW:
                        strategyData = xmlData.GetHighLowValues();
                        keyNode = "HL";
                        break;

                    case FB_Common.STRATEGIES.DOZENS:
                        strategyData = xmlData.GetDozenValues();
                        keyNode = "Dozen";
                        break;

                    case FB_Common.STRATEGIES.COLUMNS:
                        strategyData = xmlData.GetColumnValues();
                        keyNode = "CL";
                        break;

                    case FB_Common.STRATEGIES.NUMBERS:
                        strategyData = xmlData.GetNumberValues();
                        keyNode = "NO";
                        break;

                    default: return;
                }

                cboWaiting.Text = strategyData["Wait"].InnerText;

                for (int i = 1; i < 31; i++)
                {
                    ctrlName = string.Format("txtO{0}", i.ToString("00"));
                    nodeName = string.Format("{0}{1}", keyNode, i.ToString("00"));
                    grpOtherStrategy.Controls[ctrlName].Text = strategyData[nodeName].InnerText;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Loading data configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                xmlData = null;
                objData = null;
            }
        }

        #endregion

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            var confirm = MessageBox.Show("You want to reset data ?", "Data Configuration confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (confirm == System.Windows.Forms.DialogResult.OK)
            {
                LoadConfigData();
                LoadFollowingStrategy((FB_Common.STRATEGIES)cboFollowingStrategy.SelectedIndex);
                LoadOtherStrategy((FB_Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex);
            }
        }

        private void chkStrategy_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;

            if (chk.Name == chkOtherStrategy.Name)
            {
                chkFollowing.Checked = !chk.Checked;
                grpFollowing.Enabled = chkFollowing.Checked;
            }
            else
            {
                chkOtherStrategy.Checked = !chk.Checked;
                grpOtherStrategy.Enabled = chkOtherStrategy.Checked;
            }
        }

        private void cboFollowingStrategy_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadFollowingStrategy((FB_Common.STRATEGIES)cboFollowingStrategy.SelectedIndex);
        }

        private void cboTypeOfStrategy_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadOtherStrategy((FB_Common.STRATEGIES)cboTypeOfStrategy.SelectedIndex);
        }
    }
}